package com.qdxwx.manage.config;

import com.qdxwx.common.config.UploadConfig;

import com.qdxwx.manage.interceptor.LoginInterceptor;
import com.qdxwx.manage.interceptor.RepeatSubmitInterceptor;
import com.qdxwx.manage.interceptor.SessionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 通用配置
 * 
 * @author qdxwx
 */
@Configuration
public class ResourcesConfig implements WebMvcConfigurer
{

    @Autowired
    private RepeatSubmitInterceptor repeatSubmitInterceptor;

    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        ApplicationHome home = new ApplicationHome(getClass());
        registry.addResourceHandler("/**").addResourceLocations("file:" + home.getSource().getParentFile().toString() + "\\root\\");
        registry.addResourceHandler("/upload/**").addResourceLocations("file:" + UploadConfig.uploadRoot + "/upload/");
        registry.addResourceHandler("/temps/**").addResourceLocations("file:" + UploadConfig.uploadRoot + "/temps/");
    }

    /**
     * 自定义拦截规则
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry)
    {
        registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**");
        registry.addInterceptor(loginInterceptor)
                .excludePathPatterns("/static/**")
                .excludePathPatterns("/auth/**")
                .addPathPatterns("/**");
    }

    //注册session监听器;
    @Bean
    public ServletListenerRegistrationBean<SessionListener> servletListenerRegistrationBean() {
        ServletListenerRegistrationBean<SessionListener> slrBean = new ServletListenerRegistrationBean<>();
        slrBean.setListener(new SessionListener());
        return slrBean;
    }
}